package com.taoes.simpledocker.aop.aspect;

import com.taoes.simpledocker.aop.annotation.OperateRecorder;
import com.taoes.simpledocker.config.DockerClientInterception;
import com.taoes.simpledocker.model.OperateRecord;
import com.taoes.simpledocker.model.enums.OperatorResource;
import com.taoes.simpledocker.service.OperateRecordService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @BelongsProject: SimpleDocker
 * @BelongsPackage: com.taoes.simpledocker.aop.aspect
 * @Author: lfsong
 * @CreateTime: 2022-11-08  14:51
 * @Description: TODO
 * @Version: 1.0
 */

@Component
@Aspect
public class OperateRecorderAspect {

    @Resource
    OperateRecordService operateRecordService;


    @Pointcut("@annotation(e)")
    public void operateRecordPoint(OperateRecorder e) {
    }

    @AfterReturning(value = "operateRecordPoint(e)")
    public void afterOperate(JoinPoint point, OperateRecorder e) {

        System.out.println("执行afterOperate");
        OperatorResource type = e.type();
        Object[] args = point.getArgs(); // 参数值
        MethodSignature signature = (MethodSignature)point.getSignature();
        String methodName = signature.getMethod().getName();
        String[] argNames = signature.getParameterNames();
        final String clientId = DockerClientInterception.clientIdLocal.get();

        try {
            Map<String, String> param = new HashMap<>();
            for (int i = 0; i < argNames.length; i++) {
                param.put(argNames[i], args[i].toString());
            }

            OperateRecord record = new OperateRecord();
            record.setUserId(1L)
                    .setClientId(Optional.ofNullable(clientId).orElse("xxx"))
                    .setContent(param)
                    .setName(methodName)
                    .setResource(type);
            operateRecordService.add(record);
        } catch (Exception ex) {
            throw new RuntimeException("afterOperate错误："+ex.getMessage());
        }

    }


}
